package digui;

import java.util.ArrayList;
import java.util.List;

public class HappyMax {
    public static void main(String[] args) {
        // 创建员工对象
        Employee e1 = new Employee(1, new ArrayList<>());
        Employee e2 = new Employee(2, new ArrayList<>());
        Employee e3 = new Employee(3, new ArrayList<>());
        Employee e4 = new Employee(4, new ArrayList<>());
        Employee e5 = new Employee(5, new ArrayList<>());
        Employee e6 = new Employee(6, new ArrayList<>());

        // 构建员工树结构
        List<Employee> e1Nexts = new ArrayList<>();
        e1Nexts.add(e2);
        e1Nexts.add(e3);
        e1.nexts = e1Nexts;

        List<Employee> e2Nexts = new ArrayList<>();
        e2Nexts.add(e4);
        e2Nexts.add(e5);
        e2.nexts = e2Nexts;

        List<Employee> e3Nexts = new ArrayList<>();
        e3Nexts.add(e6);
        e3.nexts = e3Nexts;

        // 创建 HappyMax 对象并调用 maxHappy 方法
        HappyMax happyMax = new HappyMax();
        int maxHappy = happyMax.maxHappy(e1);
        System.out.println("最大快乐值: " + maxHappy);
    }

    static class Employee {
        int happy;
        List<Employee> nexts;

        public Employee(int happy, List<Employee> nexts) {
            this.happy = happy;
            this.nexts = nexts;
        }
    }

    public int maxHappy(Employee boss) {
        if (boss == null) {
            return 0;
        }
        Info bossInfo = process(boss);
        return Math.max(bossInfo.laiMaxHappy, bossInfo.buMaxHappy);
    }

    class Info {
        int laiMaxHappy;
        int buMaxHappy;

        public Info(int laiMaxHappy, int buMaxHappy) {
            this.laiMaxHappy = laiMaxHappy;
            this.buMaxHappy = buMaxHappy;
        }
    }

    public Info process(Employee boss) {
        if (boss.nexts == null || boss.nexts.isEmpty()) {
            return new Info(boss.happy, 0);
        }
        int lai = boss.happy;
        int bu = 0;
        for (Employee next : boss.nexts) {
            Info nextInfo = process(next);
            lai += nextInfo.buMaxHappy;
            bu += Math.max(nextInfo.laiMaxHappy, nextInfo.buMaxHappy);
        }
        return new Info(lai, bu);
    }
}
